package org.dromara.system.domain.bo.config;

import com.alibaba.fastjson2.JSONObject;
import lombok.Data;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.system.domain.PayType;

import java.util.List;
import java.util.Objects;

@Data
public class ApiConfig {

    private String label;
    private String value;
    private Integer autoFail;
    private String plugin;
    private String payName;
    private UpdateStatus updateStatus;
    private List<PayMethod> payMethod;

    //*** 主动获取支付状态 ***
    @Data
    public static class UpdateStatus {
        private Integer count;
        private Integer interval;
    }

    //*** 支付方式配置 ***
    @Data
    public static class PayMethod {
        private String label;
        private String value;
        private Integer innerType; //内嵌类型 0 wp插件内嵌，带金额  1 wp插件内嵌   2 直连内嵌   3 支付链接作为内嵌链接
        private Boolean inner = Boolean.FALSE;
        private Boolean innerPay = Boolean.FALSE;
    }

    /**
     * 获取API配置
     *
     * @param config    平台配置
     * @param apiType api类型
     * @return API配置
     */
    public static ApiConfig getConfig(String config, String apiType) {
        if (StringUtils.isEmpty(config) || StringUtils.isEmpty(apiType)) {
            return null;
        }
        JSONObject json = JSONObject.parseObject(StringUtils.removeComments(config));
        List<ApiConfig> apiConfigs = json.getList("apiConfig", ApiConfig.class);

        //获取对应API类型的插件地址
        for (ApiConfig apiConfig : apiConfigs) {
            if (Objects.equals(apiConfig.getValue(), apiType)) {
                return apiConfig;
            }
        }

        return null;
    }

    /**
     * 获取支付方式配置
     *
     * @param config    api配置
     * @param payMethod 支付方式
     * @return 支付方式
     */
    public static ApiConfig.PayMethod getPayMethod(ApiConfig config, Integer payMethod) {

        String payMethodStr = String.valueOf(payMethod);

        if (config == null || StringUtils.isEmpty(payMethodStr)) {
            return null;
        }

        List<ApiConfig.PayMethod> payMethods = config.getPayMethod();
        if (payMethods == null) {
            return null;
        }

        for (ApiConfig.PayMethod method : payMethods) {
            if (Objects.equals(method.getValue(), payMethodStr)) {
                return method;
            }
        }

        return null;
    }
}
